<template>
  <div class="fk_home">
    <div id="map" class="map"></div>
    <!-- 地图左侧 -->
    <transition name="el-fade-in-linear">
      <map-left class="map_left" v-show="isShowLeft" @handShowHospital="handShowHospital" @handShowVenue="handShowVenue"
        @handShowAmbulance="handShowAmbulance" @handleSurplus="handleSurplus"
        @sendDACRequestRes="receiveDACRequestRes"></map-left>
    </transition>
    <!-- 图例 -->
    <transition name="el-fade-in-linear">
      <div class="map_left_bottom" v-show="isShowLeft">
        <left-bottom @handleShowWhich="handleShowWhichPar" />
      </div>
    </transition>

    <!-- 地图右侧 -->
    <transition name="el-fade-in-linear">
      <div class="map_right">
        <map-right @getLinePosition="handleLinePosition" @clearLine="handleClearLine" />
      </div>
    </transition>
    <!-- 地图右侧按钮子弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="show_dialog">
        <e-m-record />
        <regulation-measure />
        <emergency-plan />
      </div>
    </transition>

    <!-- 地图左侧定点医院，场馆信息，车辆信息弹窗 -->
    <!-- 医院列表 -->
    <transition name="el-fade-in-linear">
      <div class="hospital_dialog" v-show="isShowHospitalDialog">
        <div class="tree_icon">
          <el-icon style="float: right" @click="closeHospitalDiClick">
            <close />
          </el-icon>
        </div>
        <br /><br />
        <div style="text-align: center">
          <el-input v-model="filterTextHosp" placeholder="定点医院查找" style="width: 90%; margin-bottom: 10px" />
        </div>
        <el-scrollbar height="390px">
          <!--   -->
          <el-tree ref="treeRefHosp" class="filter-tree" :data="hospitalTreeRemote" @node-click="handleHospNodeClick"
            :filter-node-method="filterNode" :props="defaultProps" default-expand-all>
          </el-tree>
        </el-scrollbar>
      </div>
    </transition>
    <!-- 场馆列表 -->
    <transition name="el-fade-in-linear">
      <div class="venue_dialog" v-show="isShowVenueDialog">
        <div class="tree_icon">
          <el-icon style="float: right" @click="closeVenueDiClick">
            <close />
          </el-icon>
        </div>
        <br /><br />
        <div style="text-align: center">
          <el-input v-model="filterTextVenu" placeholder="场馆查找" style="width: 90%; margin-bottom: 10px" />
        </div>
        <el-scrollbar height="390px">
          <el-tree ref="treeRefVenu" class="filter-tree" :data="venueTreeRemote" :props="defaultProps"
            @node-click="handleVenueNodeClick" :filter-node-method="filterNode" default-expand-all>
          </el-tree>
        </el-scrollbar>
      </div>
    </transition>
    <!-- 车辆列表 -->
    <transition name="el-fade-in-linear">
      <div class="ambulance_dialog" v-show="isShowAmbulanceDialog">
        <div class="tree_icon">
          <el-icon style="float: right" @click="closeAmDiClick">
            <close />
          </el-icon>
        </div>
        <br /><br />
        <div style="text-align: center">
          <el-input v-model="filterTextAmbu" placeholder="车辆查找" style="width: 90%; margin-bottom: 20px" />
        </div>
        <el-scrollbar height="390px">
          <el-tree ref="treeRefAmbu" class="filter-tree" :data="ambulanceTreeRemote" :props="defaultProps"
            @node-click="handleAmbuNodeClick" :filter-node-method="filterNode" default-expand-all>
          </el-tree>
        </el-scrollbar>
      </div>
    </transition>
    <!-- 药品药材不足的医疗点列表 -->
    <transition name="el-fade-in-linear">
      <div class="drug_venue_dialog" v-show="isShowDrugConsumDialog">
        <div class="tree_icon">
          <el-icon style="float: right" @click="closeDrugConsumClick">
            <close />
          </el-icon>
        </div>
        <br /><br />
        <div style="text-align: center">
          <el-input v-model="filterTextDrugConsum" placeholder="药品耗材不足医疗点搜索" style="width: 90%; margin-bottom: 10px" />
        </div>
        <el-tree ref="treeRefDrugConsum" class="filter-tree" :data="DACInsufficientTree" :props="defaultProps"
          @node-click="handleDrugNodeClick" :filter-node-method="filterNode" default-expand-all>
        </el-tree>
      </div>
    </transition>
    <!-- 场馆中按钮子弹窗 -->
    <!-- 赛程弹窗组件 -->
    <game-schedule></game-schedule>
    <!-- 医疗点弹窗组件 -->
    <medical-group :showMedicalGroupFlag="showMedicalGroupFlag" :doctorData="doctorData"
      :nurseData="nurseData"></medical-group>
    <!-- 场馆车辆弹窗组件 -->
    <venue-ambu :showVenueAmbuFlag="showVenueAmbuFlag" :venueAmbuData="venueAmbuData"></venue-ambu>
    <!-- 场馆药品耗材弹窗组件 -->
    <venue-grugs :showDrugFlag="showDrugFlag" :DACTableData="DACTableData"></venue-grugs>

    <!-- 控制先隐藏按钮 -->
    <el-button type="" plain @click="handleShowLeft" style="position: absolute; bottom: 0px; left: 0px;">
      <template #icon>
        <el-icon>
          <Hide v-if="!isShowLeft" />
          <View v-else />
        </el-icon>
      </template>
      <span>左侧栏</span>
    </el-button>

    <el-button title="清除地图上的车辆标签图层" type="" plain @click="handleHideAmbuTag"
      style="position: absolute; bottom: 210px; left: -12px;">
      <template #icon>
        <el-icon>
          <DeleteFilled />
        </el-icon>
      </template>
      <span>车标签</span>
    </el-button>
    <div class='poyline'>
      <el-progress :percentage="100" status="success">
        跑步
      </el-progress>
      <el-progress :percentage="100" status="warning">游泳
      </el-progress>
      <el-progress :percentage="100" status="exception">自行车
      </el-progress>
    </div>
  </div>
</template>

<script>
import BMapGL from 'BMapGL';
import {
  reactive, toRefs, onBeforeMount, onMounted, ref, watch, getCurrentInstance, inject, onUnmounted
} from 'vue';
import { useStore } from 'vuex';
// 全局事件
import VueEvent from '../../utils/event'
// network
import { GetHospitalInfo } from '../../network/hospital'
import { GetActiVenueInfo, GetActiVenueDetail, GetMatchingVenues } from '../../network/venues'
import { GetAmbulanceInfo } from '../../network/ambulance'
import { GetMedicalPointPerson, GetAmbList, GetDACList, GetInsufficient } from '../../network/hosVenAmbuListData'
// 图标弹窗
import {
  hospitalInfoContentcopy, venueContentcopy, vehicleInfoContentcopy, venueMedicalPointContentcopy,
} from './mapIconInfojs/mapIconInfousing';
// 场馆子弹窗
import GameSchedule from '../dialog/GameSchedule.vue'
import MedicalGroup from '../dialog/MedicalGroup.vue';
import VenueAmbu from '../dialog/VenueAmbu.vue';
import VenueGrugs from '../dialog/VenueGrugs.vue';
// 地图左侧栏
import MapLeft from './component/MapLeft.vue'
// 地图右侧栏
import MapRight from './component/MapRight.vue'
// 地图右侧按钮弹窗
import EMRecord from '../dialog/EMRecord.vue'
import RegulationMeasure from '../dialog/RegulationMeasure.vue'
import EmergencyPlan from '../dialog/EmergencyPlan.vue'
// 图例
import LeftBottom from './component/LeftBottom.vue'
// 自定义vuex 方法
import { setupMapState } from '../../store/utils/hook'
// 创建图标方法
import { CreateMark } from './methods/creatMarks'
// 转换经纬度
import { wgs84togcj02tobd09 } from '../../utils/84tobaiduGPS'

import { treeFormatData } from '../../modelUtils/returnModel';

import { ElMessage } from 'element-plus'
import {setupMapState} from "../../store/utils/hook"

export default {
  name: 'homeMapchanging',
  components: {
    GameSchedule, MedicalGroup, VenueAmbu, VenueGrugs, MapLeft,
    LeftBottom, MapRight, EMRecord, RegulationMeasure, EmergencyPlan
  },
  props: [],
  beforeRouteEnter(to, from, next) {
    // console.log(to, from, next)
    next(vm => {
      // console.log(vm.$store)
      try {

      } catch (error) {

      }
    })
  },
  setup() {
    let { proxy } = getCurrentInstance();
    // console.log(proxy.$store)
    const globalReload = inject('globalReload');
    // console.log(globalReload);
    //定义地图
    var map = null;
    // 实例化管理仓储
    const store = useStore();
    // console.log(store)
    // 医院ref
    const treeRefHosp = ref(null)
    // 场馆ref
    const treeRefVenu = ref(null)
    // 车辆ref
    const treeRefAmbu = ref(null)
    // 药品耗材ref
    const treeRefDrugConsum = ref(null)
    // 组件内部响应式状态
    const compState = reactive({
      ambuList: [],
      markerList: [],
      ambuCurMark: [],
      // 场馆医疗点
      showMedicalGroupFlag: 1,
      venuePersonType: [{ venDoctor: '5', venNurse: '6' }],
      doctorData: [],
      nurseData: [],
      // 场馆车辆
      showVenueAmbuFlag: 1,
      venueAmbuData: [],
      // 场馆药品耗材
      showDrugFlag: 1,
      drugConsumType: [{ drug: 1, consum: 2, }],
      DACTableData: [],

      // 左侧栏
      defaultProps: {
        children: 'children', label: 'name'
      },
      // 医院
      isShowHospitalDialog: false,
      filterTextHosp: "",
      hospitalTreeRemote: [],
      // 场馆
      isShowVenueDialog: false,
      filterTextVenu: "",
      venueTreeRemote: [],
      // 车辆
      isShowAmbulanceDialog: false,
      filterTextAmbu: "",
      ambulanceTreeRemote: [],
      // 药品耗材
      isShowDrugConsumDialog: false,
      filterTextDrugConsum: "",
      DACInsufficientTree: [],

      // 图例
      isShowLeft: true,
      // 定时器
      ambuTimer: null,
      // 两点之间的路线
      drivingLine: null,
      // 正在比赛的场馆
      venueView: [],

      // 车辆位置突出显示
      venueAmbu: [],
      ambuLayer: null,
      viewambu: null,
      layerdata: [],
      isShowVenueLayers: false
    });
    // 监听医院输入框
    watch(() => compState.filterTextHosp, (newV) => {
      // console.log(newV)
      treeRefHosp.value.filter(newV)
    })
    // 监听场馆输入框
    watch(() => compState.filterTextVenu, (newV) => {
      // console.log(newV)
      treeRefVenu.value.filter(newV)
    })
    // 监听车辆输入框
    watch(() => compState.filterTextAmbu, (newV) => {
      // console.log(newV)
      treeRefAmbu.value.filter(newV)
    })
    // 监听医疗点输入框
    watch(() => compState.filterTextDrugConsum, (newV) => {
      // console.log(newV)
      treeRefDrugConsum.value.filter(newV)
    })
    // 取store数据
    const { ACVCodesVx } = setupMapState("app", ["ACVCodesVx"])
    // 医院列表
    const { hospitalTreeRemoteVx } = setupMapState("HospVenuAmbuModule", ["hospitalTreeRemoteVx"])
    // 场馆列表
    const { venueTreeRemoteVx } = setupMapState("HospVenuAmbuModule", ["venueTreeRemoteVx"])
    // 车辆列表
    const { ambulanceTreeRemoteVx } = setupMapState("HospVenuAmbuModule", ["ambulanceTreeRemoteVx"])
    // 创建场馆下的医疗点
    const { venueMedicalPointArrVx } = setupMapState("HospVenuAmbuModule", ["venueMedicalPointArrVx"])
    /**
     * 事件处理方法 
     * */
    // 1.初始化地图方法
    const InitMyMap = (toMapCity) => {
      // console.log(map)
      map = new BMapGL.Map('map'); // 创建地图实例
      // map.centerAndZoom(new BMapGL.Point(120.214465, 30.254098), 12); // 初始化地图，设置中心点坐标和地图级别
      map.centerAndZoom(toMapCity, 12); // 初始化地图，设置中心点坐标和地图级别
      map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      map.setHeading(30); //设置地图旋转角度
      var opts3D = {
        anchor: BMAP_ANCHOR_BOTTOM_LEFT,
        offset: new BMapGL.Size(30, 120)
      };
      var navi3DCtrl = new BMapGL.NavigationControl3D(opts3D); // 添加3D控件
      map.addControl(navi3DCtrl);
      map.addControl(new BMapGL.MapTypeControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT, offset: new BMapGL.Size(30, 20) }));

      // //监听地图点击
      // map.addEventListener('click', function (e) {
      //   // alert("点击的经纬度：" + e.latlng.lng + ", " + e.latlng.lat);
      //   // getAndSetCurCity(map);
      // });
      // // 监听地图缩放级别
      // map.addEventListener('zoomstart', function (e) {
      //   console.log(map.getZoom());
      //   createPoyline()
      // });
    };
    // 过滤节点数据
    const filterNode = (value, data) => {
      if (!value) return true;
      return data.name.includes(value);
    };
    // 清除mapvgl图层
    const handleRemoveLayers = (view) => {
      // console.log(view)
      if (view != null) view.removeAllLayers();
    };
    // 创建路线方法
    const startLuXian = (pathParams) => {
      let path = [];
      let lushu = null;
      let starPoint = null;
      let endPoint = null;
      starPoint = new BMapGL.Point(pathParams.ambLng, pathParams.ambLat);
      endPoint = new BMapGL.Point(pathParams.hosLng, pathParams.hosLat);
      path.push(starPoint);
      path.push(endPoint);
      // console.log(path);
      compState.drivingLine = new BMapGL.DrivingRoute(map, {
        renderOptions: { map: map, autoViewport: true },
      });
      // console.log(starPoint, endPoint);
      compState.drivingLine.search(starPoint, endPoint);
      map.centerAndZoom(starPoint, 16);
    };
    //********************** 左侧栏医院操作*/
    // 点击显示医院列表
    const handShowHospital = (val) => {
      // console.log(val)
      compState.isShowHospitalDialog = val
      // console.log(hospitalTreeRemoteVx.value)
      compState.hospitalTreeRemote = hospitalTreeRemoteVx.value
      // 关闭场馆和车辆列表
      closeAmDiClick()
      closeVenueDiClick()
      closeDrugConsumClick()
    }
    // 点击医院跳转
    const handleHospNodeClick = (node) => {
      // console.log(node)
      map.flyTo(new BMapGL.Point(node.lng, node.lat), 17);
    }
    // 关闭定点医院信息列表
    const closeHospitalDiClick = () => {
      compState.isShowHospitalDialog = false;
      compState.filterTextHosp = '';
    };
    //********************** 左侧栏场馆操作*/
    // 点击显示场馆列表
    const handShowVenue = (val) => {
      // console.log(val)
      compState.isShowVenueDialog = val
      // console.log(hospitalTreeRemoteVx.value)
      compState.venueTreeRemote = venueTreeRemoteVx.value
      closeHospitalDiClick()
      closeAmDiClick()
      closeDrugConsumClick()
    }
    // 点击场馆跳转
    const handleVenueNodeClick = (node) => {
      // console.log(node)
      if (node.type == "VenuesType-1") {
        map.flyTo(new BMapGL.Point(node.lng, node.lat), 17);
      } else if (node.type == "医务室" || node.type == "观众" || node.type == "Fop") {
        map.flyTo(new BMapGL.Point(node.lng, node.lat), 19);
      } else {
        map.flyTo(new BMapGL.Point(node.lng, node.lat), 17);
      }

    }
    // 关闭场馆列表
    const closeVenueDiClick = () => {
      compState.isShowVenueDialog = false;
      compState.filterTextVenu = '';
    }
    //********************** 左侧栏车辆操作*/
    // 点击显示车辆列表
    const handShowAmbulance = (val) => {
      // console.log(val)
      compState.isShowAmbulanceDialog = val
      // console.log(ambulanceTreeRemoteVx.value)
      compState.ambulanceTreeRemote = ambulanceTreeRemoteVx.value
      closeHospitalDiClick()
      closeVenueDiClick()
      closeDrugConsumClick()
    }
    const handleAmbuNodeClick = (node) => {
      map.flyTo(new BMapGL.Point(node.lng, node.lat), 19);
    }
    const closeAmDiClick = () => {
      compState.isShowAmbulanceDialog = false;
      compState.filterTextAmbu = '';
    }
    //********************** 左侧栏药品耗材操作*/
    // 点击显示药品耗材医疗点列表
    const handleSurplus = (val) => {
      // console.log(val)
      compState.isShowDrugConsumDialog = val
      closeHospitalDiClick()
      closeVenueDiClick()
      closeAmDiClick()
    }
    // 点击医疗点节点
    const handleDrugNodeClick = async (node) => {
      console.log(node)
      let medicalId = node.id;
      let drugConsumList = [];
      let drugList = await GetInsufficient({ mpCode: medicalId, type: 1 });
      console.log("1", drugList);
      if (drugList.length > 0) {
        for (let i = 0; i < drugList.length; i++) {
          drugConsumList.push(drugList[i]);
        }
      }
      let consumList = await GetInsufficient({ mpCode: medicalId, type: 2 });
      console.log("2", consumList);
      if (consumList.length > 0) {
        for (let j = 0; j < consumList.length; j++) {
          drugConsumList.push(consumList[j]);
        }
      }
      console.log("3", drugConsumList);
      if (drugConsumList.length > 0) {
        drugConsumList.forEach((item) => {
          item.percentage = item.percentage + '%';
        });
      }
      compState.DACTableData = drugConsumList;
      compState.showDrugFlag++
    }
    // 关闭医疗点列表
    const closeDrugConsumClick = () => {
      compState.isShowDrugConsumDialog = false
      compState.filterTextDrugConsum = ''
    }
    // 药品耗材tree
    const receiveDACRequestRes = (data) => {
      console.log(data)
      compState.DACInsufficientTree = treeFormatData(data);
    }

    //********************** 左侧栏图例显隐藏 */
    const handleShowWhichPar = (val) => {
      // 显示哪类图标
      // console.log(val)
      // console.log(map.getOverlays())
      // 获取地图上的图标
      let overlays = (map.getOverlays()).filter(item => {
        return item.clas == "hospital" || item.clas == "venue" || item.clas == "taskvehicle" || item.clas == "onvehicle" || item.clas == "notaskvehicle" || item.clas == 'venueMedicalPoint'
      })
      // console.log("所有图标", overlays)

      if (val.length > 0) {
        let showArr = []
        let hideArr = []
        // 取要显示的图标(根据flag)
        val.forEach(valItem => {
          let showIcons = overlays.filter(overlaysItem => {
            return valItem.flag == overlaysItem.clas
          });
          showArr.push(...showIcons)
        })
        // 取隐藏的图标(根据项)
        hideArr = overlays.filter(overlaysItem => {
          return showArr.indexOf(overlaysItem) === -1
        })
        // console.log("显示的图标：", showArr, "隐藏的图标：", hideArr)
        // 处理隐藏和显示
        showArr.forEach(item => {
          item.show()
        })
        hideArr.forEach(item => {
          item.hide()
        })
      } else {
        // console.log("隐藏所有图标")
        overlays.forEach(item => {
          item.hide()
        })
      }
    }

    //********************** 右侧栏*/
    // 查看线路
    const handleLinePosition = (data) => {
      console.log(data);
      if (compState.drivingLine == null) {
        startLuXian(data);
      } else {
        compState.drivingLine.clearResults();
        startLuXian(data);
      }
    };
    // 清除线路
    const handleClearLine = (data) => {
      if (data && compState.drivingLine != null) {
        compState.drivingLine.clearResults();
      }
    }

    // 左侧显隐藏按钮
    const handleShowLeft = () => {
      compState.isShowLeft = !compState.isShowLeft
      closeHospitalDiClick()
      closeAmDiClick()
      closeVenueDiClick()
      closeDrugConsumClick()
    }
    // 车标签图层隐藏按钮
    const handleHideAmbuTag = () => {
      handleRemoveLayers(compState.viewambu);
      compState.isShowVenueLayers = false
    }
    //********************** 创建两点之间直线线路 （之后要改）*/
    const createPoylineItem = (param, arr, map, color) => {
      param.forEach((item, index) => {
        // console.log(item['Lng'])
        arr.push(new BMapGL.Point(item['Lng'], item['Lat']))
      })
      var polyline = new BMapGL.Polyline(arr, { strokeColor: color, strokeWeight: 5, strokeOpacity: 1 });   //创建折线
      map.addOverlay(polyline);
    }
    // 创建多点线路
    const createPoyline = (map) => {
      let pointArr = require("./statictestline.json")
      let swimArr = require("./lineJson/swim.json")
      let runArr = require("./lineJson/run.json")
      let bicycleArrs = require("./lineJson/bicycle.json")
      let aa = pointArr.aa
      let bb = pointArr.bb
      // console.log(pointArr)
      // let polylineArr1 = []
      // let polylineArr2 = []
      // let polylineArr3 = []
      // let polylineArr4 = []
      // let polylineArr5 = []
      // let polylineArr6 = []
      // let polylineArr7 = []
      // let polylineArr8 = []
      // let polylineArr9 = []
      // createPoylineItem(aa, polylineArr1, map)
      // createPoylineItem(bb, polylineArr2, map)
      // createPoylineItem(pointArr.cc, polylineArr3, map)
      // createPoylineItem(pointArr.dd, polylineArr4, map)
      // createPoylineItem(pointArr.ee, polylineArr5, map)
      // createPoylineItem(pointArr.ff, polylineArr6, map)
      // createPoylineItem(pointArr.gg, polylineArr7, map)
      // createPoylineItem(pointArr.hh, polylineArr8, map)
      // createPoylineItem(pointArr.ii, polylineArr9, map)

      // 游泳
      let swimPolylineArr = []
      createPoylineItem(swimArr.arr, swimPolylineArr, map, '#e6a23c')
      // 跑步
      let runPolylineArr = []
      createPoylineItem(runArr.arr, runPolylineArr, map, '#67c23a')
      // 自行车
      let bicyclePolylineArr1 = []
      let bicyclePolylineArr2 = []
      let bicyclePolylineArr3 = []
      let bicyclePolylineArr4 = []
      createPoylineItem(bicycleArrs.arr1, bicyclePolylineArr1, map, '#f56c6c')
      createPoylineItem(bicycleArrs.arr2, bicyclePolylineArr2, map, '#f56c6c')
      createPoylineItem(bicycleArrs.arr3, bicyclePolylineArr3, map, '#f56c6c')
      createPoylineItem(bicycleArrs.arr4, bicyclePolylineArr4, map, '#f56c6c')
    }
    /**
     * 工具方法
     * 定时器
     */
    // 延时器
    const sleep = (ms) => {
      return new Promise((resolve) => {
        setTimeout(resolve, ms);
      });
    };

    // 组件挂载前
    onBeforeMount(() => { });
    // 组件挂载后
    onMounted(() => {
      // 获取当前城市
      let toMapCity = store.state.app.cityNameVx != '' ? store.state.app.cityNameVx : '杭州市';
      //自定义图标
      var taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle.png'); //任务小车图标
      var ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle.png'); // 待命小车图标
      var notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle.png'); // 暂停车图标
      var hospitalIconUrl = require('../../assets/imgHome/mapIcon/hospital.png'); //医院图标
      var venueIconUrl = require('../../assets/imgHome/mapIcon/venue.png'); //场馆图标
      var venueMedicalPointIconUrl = require('../../assets/imgHome/mapIcon/medicalPoint.png'); //场馆内医疗点图标
      // 初始化地图
      InitMyMap(toMapCity);
      // 创建静态线路
      createPoyline(map)

      // 之前地图加载不出来的异常的处理
      // await sleep(1500)

      /**
       * 监听map.centerAndZoom()方法的执行
       */
      map.addEventListener('load', async function (e) {
        console.log('map load');
        try {
          // 医院数据及图标创建
          let param = ACVCodesVx.value
          GetHospitalInfo(param).then(res => {
            // console.log(res)
            if (res && res.length != 0) {
              store.dispatch('HospVenuAmbuModule/saveHospitalAct', res);
              res.forEach(item => {
                // console.log(item)
                // 转换经纬度
                let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat)
                let marker = CreateMark(hospitalIconUrl, 35, 35, LngLatObj.Lng, LngLatObj.Lat, 'hospital', item.Code)
                // 图标存进数组
                compState.markerList.push(marker)
                // 监听图标点击
                marker.addEventListener('click', function () {
                  // console.log(marker)
                  var hospid = marker.id;
                  // 根据id找到此医院
                  let curMark = res.filter((item, index) => {
                    return item.Code == hospid;
                  });
                  // 设置中心点坐标和地图级别
                  map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 18);
                  // console.log(curMark[0])
                  let opts = {
                    title: '医院信息',
                    width: 270,
                    height: 'auto',
                  };
                  let myinfoWindow = new BMapGL.InfoWindow(
                    hospitalInfoContentcopy(curMark[0]),
                    opts,
                  );
                  this.openInfoWindow(myinfoWindow);
                })
                // 1s后将医院图标添加到地图
                let timer = setTimeout(() => {
                  map.addOverlay(marker);
                  clearTimeout(timer)
                }, 500)
              })
            } else {
              console.log("homeMap/GetHospitalInfo", "医院数据返回为空")
            }
          }).catch(err => {
            console.log("homeMap/GetHospitalInfo", err)
          })

          // 场馆数据及图标创建
          await GetActiVenueInfo(param).then(res => {
            // console.log(res)
            if (res && res.length != 0) {
              store.dispatch('HospVenuAmbuModule/saveVenueAct', res,);
              res.forEach(item => {
                // 转换经纬度
                let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat)
                let marker = CreateMark(venueIconUrl, 35, 35, LngLatObj.Lng, LngLatObj.Lat, 'venue', item.Code)
                // 图标存进数组
                compState.markerList.push(marker)
                // 监听图标点击
                marker.addEventListener('click', async function () {
                  // console.log(marker)
                  var venueid = marker.id;
                  // 根据id找到此场馆
                  let curMark = res.filter((item, index) => {
                    return item.Code == venueid;
                  });
                  // 设置中心点坐标和地图级别
                  map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 18);
                  // console.log(curMark[0])
                  let opts = {
                    title: '场馆信息',
                    width: 400,
                    height: 'auto',
                  };

                  // 根据场馆id获取场馆详情
                  let venueDetail = await GetActiVenueDetail({
                    venuesCode: venueid,
                  });
                  // console.log(venueDetail)
                  if (venueDetail != null) {
                    await store.dispatch(
                      'HospVenuAmbuModule/saveVenueDetailAct',
                      venueDetail,
                    )
                  };
                  let myinfoWindow = new BMapGL.InfoWindow(
                    venueContentcopy({
                      curMark: curMark[0],
                      venueDetail: venueDetail,
                    }),
                    opts,
                  );
                  // 监听弹窗打开，再根据dom元素监听按钮点击
                  myinfoWindow.addEventListener('open', function () {
                    console.log('myinfoWindow is open')
                    // 在这里移除车辆图标图层，否则移除不成功
                    if (compState.viewambu != null) {
                      compState.viewambu.removeAllLayers();
                    }

                    // console.log(myinfoWindow.isOpen())
                    let gameScheduleDoc = document.getElementById('gameScheduleClick')
                    let medicalGroupDoc = document.getElementById('medicalGroupClick')
                    let ambulanceDoc = document.getElementById('ambulanceClick')
                    let drugDoc = document.getElementById('drugClick')
                    let venueAmbulanceShowDoc = document.getElementById('venueAmbulanceShowClick')
                    // console.log(ambulanceDoc);
                    // 赛程按钮
                    if (gameScheduleDoc.id == "gameScheduleClick") {
                      gameScheduleDoc.onclick = () => {
                        console.log("gameScheduleClick");
                        // console.log(venueid)
                        // 向弹窗发送事件
                        VueEvent.emit('showGameSchedule', {
                          isShowGameSchedule: true,
                          id: venueid,
                        });
                      }
                    }
                    // 医疗点按钮
                    if (medicalGroupDoc.id == "medicalGroupClick") {
                      medicalGroupDoc.onclick = async () => {
                        console.log("medicalGroupClick");
                        // 获取场馆医疗点数据(医生，护士都取出来)
                        // console.log(venueid);
                        let medicalPointDoctor = await GetMedicalPointPerson({
                          venuesCode: venueid,
                          personType: compState.venuePersonType[0].venDoctor,
                        });
                        let medicalPointNurse = await GetMedicalPointPerson({
                          venuesCode: venueid,
                          personType: compState.venuePersonType[0].venNurse,
                        });
                        compState.doctorData = medicalPointDoctor;
                        compState.nurseData = medicalPointNurse;
                        // console.log('医生和护士', compState.doctorData, compState.nurseData)
                        compState.showMedicalGroupFlag++
                      }
                    }
                    // 车辆按钮
                    if (ambulanceDoc.id == "ambulanceClick") {
                      // 单击显示车辆列表
                      ambulanceDoc.onclick = async () => {
                        console.log("ambulanceClick");
                        // console.log(venueid)
                        let venueAmbulance = await GetAmbList({
                          venuesCode: venueid,
                        });
                        compState.venueAmbuData = venueAmbulance
                        // console.log(compState.medicalPointAmbuData)
                        compState.showVenueAmbuFlag++
                      }
                    }

                    // 车辆位置按钮(突出显示某场馆的车辆)
                    compState.viewambu = new mapvgl.View({
                      map: map
                    })
                    compState.ambuLayer = new mapvgl.LabelLayer({
                      textAlign: 'center',
                      textColor: '#fc0',
                      borderColor: '#666',
                      backgroundColor: '#666',
                      padding: [2, 5],
                      borderRadius: 5,
                      fontSize: 12,
                      lineHeight: 16,
                      collides: true, // 是否开启碰撞检测, 数量较多时建议打开
                      enablePicked: true,
                      autoSelect: true,
                      onClick: e => {
                        // 点击事件
                        // console.log('click', e);
                      },
                    });

                    if (venueAmbulanceShowDoc.id == 'venueAmbulanceShowClick') {
                      venueAmbulanceShowDoc.onclick = async function () {
                        // 显示车辆标签图层
                        compState.isShowVenueLayers = true
                        // console.log("venueAmbulanceShowClick");
                        // console.log(venueid)
                        compState.venueAmbu = await GetAmbList({
                          venuesCode: venueid,
                        });
                        // console.log(compState.venueAmbu)

                        // 地图显示车辆信息
                        // console.log(curMark[0])

                        compState.layerdata = []
                        if (compState.venueAmbu.length > 0) {
                          compState.venueAmbu.forEach(item => {
                            let newItem = wgs84togcj02tobd09(
                              item.Lng,
                              item.Lat,
                            );
                            compState.layerdata.push({
                              ambucode: item.Code,
                              venueName: curMark[0].CHIDescription,
                              geometry: {
                                type: 'Point',
                                coordinates: [newItem.Lng, newItem.Lat]
                              },
                              properties: {
                                text: item.Name +
                                  '\n' +
                                  curMark[0].CHIDescription,
                              }
                            })
                          })

                          // mapvgl容器添加layer
                          compState.viewambu.addLayer(compState.ambuLayer);
                          // layer设置数据
                          compState.ambuLayer.setData(compState.layerdata);

                          ElMessage({
                            message: '此场馆共有车辆' + compState.venueAmbu.length + "辆",
                            type: 'success',
                          })
                        } else {
                          console.log("此场馆无车辆！")
                          ElMessage({
                            message: '此场馆无车辆！',
                            type: 'warning',
                          })
                        }
                        map.centerAndZoom(
                          new BMapGL.Point(curMark[0].Lng, curMark[0].Lat),
                          12,
                        );
                      }
                    }
                    // 药品耗材按钮
                    if (drugDoc.id == "drugClick") {
                      drugDoc.onclick = async () => {
                        console.log("drugClick");
                        // console.log(venueid)
                        var medicalPointDACArr = [];
                        let medicalPointDrug = await GetDACList({
                          venuesCode: venueid,
                          type: compState.drugConsumType[0].drug,
                        });
                        // console.log(medicalPointDrug);
                        if (medicalPointDrug.length > 0) {
                          medicalPointDrug.forEach((item) => {
                            medicalPointDACArr.push(item);
                          });
                        }

                        let medicalPointConsum = await GetDACList({
                          venuesCode: venueid,
                          type: compState.drugConsumType[0].consum,
                        });
                        if (medicalPointConsum.length > 0) {
                          medicalPointConsum.forEach((item) => {
                            medicalPointDACArr.push(item);
                          });
                        }
                        // console.log(medicalPointDACArr);
                        if (medicalPointDACArr.length > 0) {
                          medicalPointDACArr.forEach((item) => {
                            item.percentage = item.percentage + '%';
                          });
                        }
                        compState.DACTableData = medicalPointDACArr;
                        // console.log( state.DACTableData)
                        compState.showDrugFlag++;
                      }
                    }
                  })
                  // 信息窗口关闭的时候可以实时监听到
                  myinfoWindow.addEventListener('close', function () {
                    console.log('myinfoWindow', 'close', myinfoWindow.isOpen());
                    if (compState.viewambu != null) {
                      // compState.viewambu.removeAllLayers();
                    }
                  });
                  // 先进行事件监听 然后才打开图标弹窗********
                  marker.openInfoWindow(myinfoWindow);
                })
                // 1s后将场馆图标添加到地图
                let timer = setTimeout(() => {
                  map.addOverlay(marker);
                  clearTimeout(timer)
                }, 600)
              })
            } else {
              console.log("homeMap/GetActiVenueInfo", "场馆数据返回为空")
            }
          }).catch(err => {
            console.log("homeMap/GetActiVenueInfo", err)
          })

          // 场馆下的医疗点图标创建 await必须加，不然venueMedicalPointArrVx为空
          // console.log(venueMedicalPointArrVx.value)
          let venueMedicalPointArr = venueMedicalPointArrVx.value
          venueMedicalPointArr.forEach(item => {
            // console.log(item)
            // 经纬度转换过了
            let marker = CreateMark(venueMedicalPointIconUrl, 35, 35, item.lng, item.lat, 'venueMedicalPoint', item.id, item.name)
            // 图标存进数组
            compState.markerList.push(marker)
            // 监听图标点击
            marker.addEventListener('click', function () {
              // console.log(marker)
              var venueMedicalPointid = marker.id;
              // 根据id找到此医疗点
              let curMark = venueMedicalPointArr.filter((item, index) => {
                return item.id == venueMedicalPointid;
              });
              // 设置中心点坐标和地图级别
              map.flyTo(new BMapGL.Point(item.lng, item.lat), 20);
              console.log(curMark[0])
              let opts = {
                title: '医疗点信息',
                width: 270,
                height: 'auto',
              };
              let myinfoWindow = new BMapGL.InfoWindow(
                venueMedicalPointContentcopy(curMark[0]),
                opts,
              );
              this.openInfoWindow(myinfoWindow);
            })
            // 1s后将医院图标添加到地图
            let timer = setTimeout(() => {
              map.addOverlay(marker);
              clearTimeout(timer)
            }, 600)
          })

          // 车辆数据及图标创建
          GetAmbulanceInfo(param).then(res => {
            // console.log(res)
            if (res && res.length != 0) {
              store.dispatch('HospVenuAmbuModule/saveAmbulanceAct', res,);
              // 将车辆返回结果赋值给响应式对象
              compState.ambuList = res
              compState.ambuList.forEach(item => {
                // 转换经纬度
                let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat)
                // 根据任务状态判断
                switch (item.StateCode) {
                  // 任务中
                  case 0: case 1: case 2: case 3: case 4: case 5: case 101: case 102:
                    // console.log(item);
                    let marker1 = CreateMark(taskVehicleIconUrl, 35, 35, LngLatObj.Lng, LngLatObj.Lat, 'taskvehicle', item.Code, item.Name, item.Direction)
                    compState.markerList.push(marker1)
                    marker1.addEventListener('click', function () {
                      // console.log(marker1)
                      var vehicleid = marker1.id;
                      // 根据id找到此车辆
                      let ambuCurMark = compState.ambuList.filter((item, index) => {
                        return item.Code == vehicleid;
                      });
                      // 设置中心点坐标和地图级别
                      map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 20);
                      // console.log(ambuCurMark[0])
                      let opts = {
                        title: '车辆信息',
                        width: 270,
                        height: 'auto',
                      };
                      let ambuInfoWindow = new BMapGL.InfoWindow(
                        vehicleInfoContentcopy(ambuCurMark[0]),
                        opts,
                      );
                      marker1.openInfoWindow(ambuInfoWindow);
                    })
                    // 1s后将车辆图标添加到地图
                    let timer1 = setTimeout(() => {
                      map.addOverlay(marker1);
                      clearTimeout(timer1)
                    }, 700)
                    break;
                  // 待命中
                  case 6:
                  case 7:
                    let marker2 = CreateMark(ontaskVehicleIconUrl, 35, 35, LngLatObj.Lng, LngLatObj.Lat, 'onvehicle', item.Code, item.Name, item.Direction)
                    compState.markerList.push(marker2)
                    marker2.addEventListener('click', function () {
                      // console.log(marker2)
                      var vehicleid = marker2.id;
                      // 根据id找到此车辆
                      let ambuCurMark = compState.ambuList.filter((item, index) => {
                        return item.Code == vehicleid;
                      });
                      // 设置中心点坐标和地图级别
                      map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 20);
                      // console.log(ambuCurMark[0])
                      let opts = {
                        title: '车辆信息',
                        width: 270,
                        height: 'auto',
                      };
                      let ambuInfoWindow = new BMapGL.InfoWindow(
                        vehicleInfoContentcopy(ambuCurMark[0]),
                        opts,
                      );
                      marker2.openInfoWindow(ambuInfoWindow);
                    })
                    let timer2 = setTimeout(() => {
                      map.addOverlay(marker2);
                      clearTimeout(timer2)
                    }, 700)
                    break;
                  // 暂停调用
                  case 8:
                  case 9:
                    let marker3 = CreateMark(notaskVehicleIconUrl, 35, 35, LngLatObj.Lng, LngLatObj.Lat, 'notaskvehicle', item.Code, item.Name, item.Direction)
                    compState.markerList.push(marker3)
                    marker3.addEventListener('click', function () {
                      // console.log(marker3)
                      var vehicleid = marker3.id;
                      // 根据id找到此车辆
                      let ambuCurMark = compState.ambuList.filter((item, index) => {
                        return item.Code == vehicleid;
                      });
                      // 设置中心点坐标和地图级别
                      map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 20);
                      // console.log(ambuCurMark[0])
                      let opts = {
                        title: '车辆信息',
                        width: 270,
                        height: 'auto',
                      };
                      let ambuInfoWindow = new BMapGL.InfoWindow(
                        vehicleInfoContentcopy(compState.ambuCurMark[0]),
                        opts,
                      );
                      marker3.openInfoWindow(ambuInfoWindow);
                    })
                    let timer3 = setTimeout(() => {
                      map.addOverlay(marker3);
                      clearTimeout(timer3)
                    }, 700)
                    break;
                  default:
                    break;
                }
              })
            } else {
              console.log("homeMap/GetAmbulanceInfo", "车辆数据返回为空")
            }
          }).catch(err => {
            console.log(err)
          });

          //获取正在举行的场馆并在地图标注
          GetMatchingVenues(param).then((res) => {
            // console.log(res);
            // 存正在比赛场馆的经纬度
            var lngAndLats = [];
            if (res.length > 0) {
              res.forEach((item) => {
                lngAndLats.push({ lng: item.Lng, lat: item.Lat });
              });
              compState.venueView = new mapvgl.View({
                map: map,
              });
              var colors = ['#f00', '#ff0', '#0ff', '#00f'];
              var data = lngAndLats.map((item, index) => {
                let newItem = wgs84togcj02tobd09(item.lng, item.lat);
                // console.log(newItem);
                return {
                  geometry: {
                    type: 'Point',
                    coordinates: [newItem.Lng, newItem.Lat],
                  },
                  color: colors[0],
                  // 圆的半径
                  size: 5,
                };
              });
              var bubbleLayer = new mapvgl.CircleLayer({
                // 绘制带泡泡的圆
                type: 'bubble',
                size: (size) => 1 * size,
                // 扩散半径，支持直接设置和回调两种形式，size为点的大小
                radius(size) {
                  return 5 * size;
                },
                // 扩散时间
                duration: 1,
                // 渐隐时间
                trail: 1,
              });
              compState.venueView.addLayer(bubbleLayer);
              bubbleLayer.setData(data);
            } else {
              console.log('没有正在举办比赛的场馆！')
            }
          })
            .catch((err) => {
              console.log(err);
            });

          // 定时循环刷新车辆位置及状态信息
          compState.ambuTimer = setInterval(() => {
            // compState.ambuTimer = setTimeout(() => {
            // 获取地图上所有标注
            let mapOverlays = map.getOverlays()
            // console.log(mapOverlays)
            GetAmbulanceInfo(param).then(res => {
              // console.log(res)
              compState.ambuList = res
              store.dispatch('HospVenuAmbuModule/saveAmbulanceAct', res,);
              compState.ambulanceTreeRemote = ambulanceTreeRemoteVx.value
              // 先获取图标中的车辆类型的标注
              let ambuMarkerArr = mapOverlays.filter(item => {
                // console.log(item.clas)
                return item.clas == "taskvehicle" || item.clas == "onvehicle" || item.clas == "notaskvehicle"
              })
              // console.log(ambuMarkerArr)

              ambuMarkerArr.forEach(makerItem => {
                compState.ambuList.forEach(item => {
                  if (makerItem.id == item.Code) {
                    // 转换经纬度
                    let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat)
                    // console.log(makerItem)
                    // 设置位置
                    makerItem.setPosition(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat))
                    // 设置旋转角度
                    makerItem.setRotation(item.Direction);
                    // 获取图标文本标注对象，方便设置样式
                    let label = makerItem.getLabel()

                    // 根据车辆状态设置车辆图标
                    switch (item.StateCode) {
                      // 任务中
                      case 0: case 1: case 2: case 3: case 4: case 5: case 101: case 102:
                        makerItem.setIcon(new BMapGL.Icon(taskVehicleIconUrl, new BMapGL.Size(35, 35)))
                        // console.log(makerItem.getLabel())
                        // 设置文本标注颜色
                        label.setStyle({
                          color: 'red'
                        })
                        break;
                      // 待命中
                      case 6:
                      case 7:
                        makerItem.setIcon(new BMapGL.Icon(ontaskVehicleIconUrl, new BMapGL.Size(35, 35)))
                        label.setStyle({
                          color: 'blue'
                        })
                        break;
                      // 暂停调用
                      case 8:
                      case 9:
                        makerItem.setIcon(new BMapGL.Icon(notaskVehicleIconUrl, new BMapGL.Size(35, 35)))
                        label.setStyle({
                          color: 'gray'
                        })
                        break;
                      default:
                        break;
                    }
                  }
                })
              })

              // 更新车辆标签图层
              // console.log(compState.isShowVenueLayers)

              // 当车辆标签图层存在数据并且显示时，定时器生效，刷新车辆
              if (compState.isShowVenueLayers) {
                let ambulayerData = compState.ambuLayer.getData()
                if (ambulayerData.length > 0) {
                  // 获取场馆名称
                  let venueName = ambulayerData[0].venueName
                  //  console.log(venueName) 
                  compState.layerdata = []
                  // 遍历场馆下车辆(compState.venueAmbu是第一次点击缓存的数据，只要上面的if条件通过compState.venueAmbu不为空)
                  // res 是所有的车辆，根据车辆编码筛选某场馆的车辆
                  // console.log("场馆车辆：", compState.venueAmbu)
                  res.forEach(resItem => {
                    compState.venueAmbu.forEach(item => {
                      if (resItem.Code == item.Code) {
                        // console.log(item)
                        let newItem = wgs84togcj02tobd09(
                          resItem.Lng,
                          resItem.Lat,
                        );
                        compState.layerdata.push({
                          ambucode: item.Code,
                          venueName: venueName,
                          geometry: {
                            type: 'Point',
                            coordinates: [newItem.Lng, newItem.Lat]
                          },
                          properties: {
                            text: item.Name +
                              '\n' +
                              venueName,
                          }
                        })
                      }
                    })
                  })
                  // layer重新设置数据
                  compState.ambuLayer.setData(compState.layerdata);
                  console.log("重新设置了车辆标签图层！")
                }
              }
            }).catch(err => {
              console.log(err)
            })
          }, 10000)
        }
        catch (error) {
          console.log("homeMap", error)
        }
      });
    });
    // 事件总线监听页面刷新
    VueEvent.on('refreshHome', async (data) => {
      if (data && data.isRefresh) {
        // console.log("重新加载页面")
        await globalReload();
      }
    });
    onUnmounted(() => {
      clearInterval(compState.ambuTimer)
      // clearTimeout(compState.ambuTimer)
      compState.ambuTimer = null
      console.log("homeMap/清除了车辆循环刷新定时器！");
    });
    const refState = toRefs(compState);
    return {
      // 状态
      ...refState,
      map,
      treeRefHosp,
      treeRefVenu,
      treeRefAmbu,
      treeRefDrugConsum,
      // 事件
      InitMyMap,
      CreateMark,
      filterNode,
      // 医院
      handShowHospital,
      closeHospitalDiClick,
      handleHospNodeClick,
      // 场馆
      handleVenueNodeClick,
      handShowVenue,
      closeVenueDiClick,
      // 车辆
      handShowAmbulance,
      handleAmbuNodeClick,
      closeAmDiClick,
      // 药品耗材
      handleSurplus,
      handleDrugNodeClick,
      closeDrugConsumClick,
      receiveDACRequestRes,
      // 图例
      handleShowWhichPar,
      // 地图右侧
      handleLinePosition,
      handleClearLine,
      // 显隐藏按钮
      handleShowLeft,
      handleHideAmbuTag
    };
  },
};
</script>
<style scoped>
.map {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 0;
}

/* 地图左侧 */
.map_left {
  position: absolute;
  margin: 3px;
  z-index: 1;
}

/* 地图右侧 */
.map_right {
  width: 520px;
  position: absolute;
  right: 3px;
  margin-top: 3px;
}

/* 地图左下角 */
/* .map_left_bottom {
  position: absolute;
  bottom: 5px;
  left: 100px;
  z-index: 1;
} */

.fk_home .ambulance_dialog,
.fk_home .venue_dialog,
.fk_home .hospital_dialog,
.fk_home .drug_venue_dialog {
  position: absolute;
  height: 500px;
  width: 300px;
  background: #fff;
  left: 260px;
  top: 5px;
}

/* .fk_home .drug_venue_dialog {
  position: absolute;
  height: 300px;
  width: 220px;
  background: #fff;
  left: 260px;
  top: 400px;
} */

/* 地图图标显示窗口 */
:deep(.BMap_bubble_pop) {
  padding: 0 !important;
}

:deep(.BMap_bubble_top) {
  background: #758bfd !important;
}

:deep(.BMap_bubble_top .BMap_bubble_title) {
  margin-left: 5px !important;
}

/* // 去掉文字那行，添加CSS即可 */
:deep(.BMap_cpyCtrl) {
  display: none;
}

.fk_home .tree_icon {
  cursor: pointer;
  position: relative;
  top: 5px;
  right: 5px;
}

.fk_home .tree_icon:hover {
  color: #758bfd;
}

.poyline {
  position: absolute;
  bottom: 5px;

  background-color: rgba(255, 255, 255, 0.7);
  width: 150px;
  height: 50px;
  border-radius: 5px;
  padding: 5px;
}

@media screen and (max-height:950px) {
  .poyline {
    left: 780px;
  }
}

@media screen and (min-height:950px) {
  .poyline {
    left: 280px;
  }

}
</style>
